package com.cl.spark.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
    public static void main(String[] args) {
        String input = "上城区茅家埠1 - 31(自主申报)（123）";
        String output = extractChineseAndAlphanumeric(input);
        System.out.println(output);  // 输出: Hello世界123Howareyou456
    }

    public static String extractChineseAndAlphanumeric(String str) {
        // 1. 去除中文括号（（））及其内部内容
        str = str.replaceAll("（[^）]*）", "");

        // 2. 去除英文括号（()）及其内部内容
        str = str.replaceAll("\\([^)]*\\)", "");

        // 3. 提取中文、字母和数字
        return str.replaceAll("[^\\u4e00-\\u9fa5a-zA-Z0-9]", "");
    }

    public static List<String> extractSQLTableNames(String sql) {
        List<String> tableNames = new ArrayList<>();

        // Convert the SQL statement to uppercase for easier pattern matching
        String upperSql = sql.toUpperCase();

        // Define patterns for different SQL operations
        Pattern selectPattern = Pattern.compile("\\bFROM\\s+(\\w+)(?:\\s+AS\\s+\\w+)?", Pattern.CASE_INSENSITIVE);
        Pattern insertPattern = Pattern.compile("\\bINTO\\s+(\\w+)", Pattern.CASE_INSENSITIVE);
        Pattern updatePattern = Pattern.compile("\\bUPDATE\\s+(\\w+)(?:\\s+AS\\s+\\w+)?", Pattern.CASE_INSENSITIVE);
        Pattern deletePattern = Pattern.compile("\\bFROM\\s+(\\w+)(?:\\s+AS\\s+\\w+)?", Pattern.CASE_INSENSITIVE);

        // Matcher for SELECT statements
        Matcher matcher = selectPattern.matcher(upperSql);
        while (matcher.find()) {
            tableNames.add(matcher.group(1));
        }

        // Matcher for INSERT statements
        matcher = insertPattern.matcher(upperSql);
        while (matcher.find()) {
            tableNames.add(matcher.group(1));
        }

        // Matcher for UPDATE statements
        matcher = updatePattern.matcher(upperSql);
        while (matcher.find()) {
            tableNames.add(matcher.group(1));
        }

        // Matcher for DELETE statements
        matcher = deletePattern.matcher(upperSql);
        while (matcher.find()) {
            tableNames.add(matcher.group(1));
        }

        return tableNames;
    }

}
